package com.googlecode.gwtbb.server.intermediate.forum;

import com.googlecode.gwtbb.client.shared.entity.forum.Forum;
import com.googlecode.gwtbb.client.shared.entity.forum.Post;
import com.googlecode.gwtbb.server.dao.forum.ForumDao;
import com.googlecode.gwtbb.server.dao.forum.ForumInfoDao;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Abraham Grief
 * @version $Id$
 * @since Jul 7, 2008
 */
public class ForumAssembler {
	private ForumDao forumDao;
	private ForumInfoDao forumInfoDao;
	private PostAssembler postAssembler;

	public ForumDao getForumDao() {
		return forumDao;
	}

	public void setForumDao(ForumDao forumDao) {
		this.forumDao = forumDao;
	}

	public ForumInfoDao getForumInfoDao() {
		return forumInfoDao;
	}

	public void setForumInfoDao(ForumInfoDao forumInfoDao) {
		this.forumInfoDao = forumInfoDao;
	}

	public PostAssembler getPostAssembler() {
		return postAssembler;
	}

	public void setPostAssembler(PostAssembler postAssembler) {
		this.postAssembler = postAssembler;
	}

	@Transactional
	public List<Forum> assemble(List<Forum> forums) {
		for (Forum forum : forums)
			assemble(forum);
		return forums;
	}

	@Transactional
	public Forum assemble(Long forumId) {
		return assemble(forumDao.select(forumId));
	}

	@Transactional
	public Forum assemble(Forum forum) {
		if (forum != null) {
			Forum.Info forumInfo = forumInfoDao.select(forum.getId());
			if (forumInfo != null) {
				forum.setInfo(forumInfo);
				Long lastPostId = forumInfo.getLastPostId();
				if (lastPostId != null) {
					Post lastPost = postAssembler.assemble(lastPostId);
					forumInfo.setLastPost(lastPost);
				}
			}
		}
		return forum;
	}

	@Transactional
	public List<Forum> assembleAll() {
		return assemble(forumDao.selectAll());
	}
}
